package com.youhome.common.handler;

import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.persistence.PersistenceException;
import javax.security.auth.login.LoginException;

/**
 * Created by chen365 on 2019/01/29.
 */
//@ControllerAdvice
@Slf4j
public class AllExceptionHandler {

    @ExceptionHandler(value = LoginException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public Object loginExceptionHandler() {
        log.error("登陆异常");
        return new Result<>(ResultCode.EXPIRED_LOGIN);
    }


    @ExceptionHandler
    @ResponseBody
    public Object allExceptionHandler(Exception e) {
        log.info("================【开始打印异常信息】================");
        log.error("具体错误信息:【" + e.getMessage() + "】");
        int count = 0; //只打印15行的错误堆栈
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            log.error(stackTraceElement.toString());
            if (count++ > 13) break;
        }
        log.info("================【异常信息打印完毕】================");
        if (e instanceof CustomException) {
            return new Result<>(((CustomException) e).getResultCode(), e.getMessage());
        }
        if (e instanceof IllegalArgumentException || e instanceof IllegalStateException) {
            return new Result<>(ResultCode.ERROR_PARAMETER, e.getMessage());
        }
        if (e instanceof PersistenceException || e instanceof BadSqlGrammarException) {
            return new Result<>(ResultCode.ERROR_SQL);
        }
        if (e instanceof NullPointerException) {
            return new Result<>(ResultCode.FAIL, e.getMessage());
        }
        return new Result<>(ResultCode.FAIL);
    }


}
